package com.m31skytech.dungeonstool.blocks;

import com.m31skytech.dungeonstool.ItemRegistry;
import com.m31skytech.dungeonstool.blockentitys.TeleportControlBlockEntity;
import com.m31skytech.dungeonstool.blockentitys.TeleportPointBlockEntity;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Registry;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.EntityBlock;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockBehaviour;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.material.Material;
import net.minecraft.world.phys.BlockHitResult;
import org.jetbrains.annotations.NotNull;

import javax.annotation.Nullable;
import java.util.Objects;

public class TeleportPointBlock extends Block implements EntityBlock {

    public TeleportPointBlock() {
        super(BlockBehaviour.Properties.of(Material.STONE)
                .strength(-1f, 3600000.0F)
                .requiresCorrectToolForDrops());
    }

    @Nullable
    @Override
    public BlockEntity newBlockEntity(@NotNull BlockPos pos, @NotNull BlockState state) {
        return new TeleportPointBlockEntity(pos, state);
    }

    @Override
    public InteractionResult use(BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand
            , BlockHitResult hit) {
        ItemStack heldItem = player.getMainHandItem();

        // 检查玩家是否手持 DTWands
        if (heldItem.getItem() == ItemRegistry.DT_WANDS.get()) {
            //确保数据逻辑仅发生在服务端
            if (!world.isClientSide) {
                //若当前副本传送点已经被绑定,在手持副本权杖的前提下，提示shift+右键 可解除原始绑定
                if(alreadyBind(pos,world)){
                    return alreadyBindHandler(pos,world,player);
                }else {
                    return doBindingHandler(pos, world, player);
                }
            }
            return InteractionResult.SUCCESS; // 处理了事件，返回 SUCCESS
        }
        return super.use(state, world, pos, player, hand, hit);
    }

    /**判断当前传送点方块是否已被绑定
     *
     * @param pos
     * @param world
     * @return
     */
    private boolean alreadyBind(BlockPos pos,Level world){
        TeleportPointBlockEntity pointBlockEntity = (TeleportPointBlockEntity) world
                .getBlockEntity(pos);
        if (null!=pointBlockEntity){
            return pointBlockEntity.isBound();
        }
        return false;
    }

    /**已绑定条件下的处理分支
     *
     * @param pos
     * @param world
     * @param player
     * @return
     */
    private InteractionResult alreadyBindHandler(BlockPos pos,Level world,Player player){
        TeleportPointBlockEntity pointBlockEntity = (TeleportPointBlockEntity) world
                .getBlockEntity(pos);
        assert pointBlockEntity != null;
        BlockPos bindPosOrigin = pointBlockEntity.getBindPos();
        Component message =
                Component.literal("该传送点方块(" + pos.getX() + ", " + pos.getY() + ", " + pos.getZ() + ")已被绑定,源(" +
                        bindPosOrigin.getX()+","+bindPosOrigin.getY()+", "+bindPosOrigin.getZ()+"\n")
                        .append(pointBlockEntity.getBindDimension().location()+
                                "), 可通空手右击与源传送方块进行交互.");
        player.displayClientMessage(message, true);
        return InteractionResult.SUCCESS; // 处理了事件，返回 SUCCESS
    }

    /**未绑定条件下的绑定逻辑
     *
     * @param pos
     * @param world
     * @param player
     * @return
     */
    private InteractionResult doBindingHandler(BlockPos pos,Level world,Player player){
        // 获取之前存储的传送控制方块坐标
        int[] selectedControlBlockPos = player.getPersistentData().getIntArray("selectedControlBlock");
        String dimension = player.getPersistentData().getString("selectedControlBlockDimension");
        ResourceLocation dimensionLocation = new ResourceLocation(dimension);

        if (selectedControlBlockPos.length == 3) {
            BlockPos controlBlockPos =
                    new BlockPos(selectedControlBlockPos[0], selectedControlBlockPos[1]
                            , selectedControlBlockPos[2]);

            Level controlBlockPosLevel = Objects.requireNonNull(world.getServer())
                    .getLevel(ResourceKey.create(Registry.DIMENSION_REGISTRY, dimensionLocation));


            //传送控制方块
            assert controlBlockPosLevel != null;
            TeleportControlBlockEntity controlBlockEntity = (TeleportControlBlockEntity) controlBlockPosLevel
                    .getBlockEntity(controlBlockPos);
            //传送点方块
            TeleportPointBlockEntity pointBlockEntity = (TeleportPointBlockEntity) world
                    .getBlockEntity(pos);

            if (controlBlockEntity != null && null!= pointBlockEntity) {
                //双向绑定
                controlBlockEntity.setBindPos(pos,world);

                pointBlockEntity.setBindPos(controlBlockPos,controlBlockPosLevel);
                // 提示绑定成功
                player.displayClientMessage(Component.literal("绑定成功！"), true);
                // 清除存储的传送控制方块坐标
                player.getPersistentData().remove("selectedControlBlock");
                player.getPersistentData().remove("selectedControlBlockDimension");
            }
        }else{
            // 提示需要绑定副本传送方块
            player.displayClientMessage(
                    Component.literal("请先使用副本权杖右击绑定副本传送控制方块！"), true);

        }
        return InteractionResult.SUCCESS; // 处理了事件，返回 SUCCESS
    }
}
